package com.zm.demo.netty.server.http;

import com.google.gson.JsonObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * @author z01140
 * @Package: com.zm.demo.netty.server.http
 * @Description:
 * @CreateDate 2023/8/31 10:01
 * @UpdateDate 2023/8/31 10:01
 */
public class HttpServerHandler1 extends SimpleChannelInboundHandler<FullHttpRequest> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
        System.out.println("uri=" + msg.uri() + ", method=" + msg.method().name());
        ByteBuf byteBuf = msg.content();
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(msg.uri());
        queryStringDecoder.parameters();

//        System.out.println("request_queryString=" + queryStringDecoder.parameters().toString());

        ByteBuf byteBuf1 = Unpooled.copiedBuffer(byteBuf.toString(io.netty.util.CharsetUtil.UTF_8) + " " + queryStringDecoder.parameters().toString() , CharsetUtil.UTF_8);
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf1);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain;charset=utf8");
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf1.readableBytes());
        System.out.println("response: " + byteBuf.toString(CharsetUtil.UTF_8));
        ctx.writeAndFlush(response);

    }
}
